package com.cuit.controller;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.io.resource.Resource;
import com.cuit.common.Constants;
import com.cuit.common.PageResult;
import com.cuit.common.Result;
import com.cuit.entity.User;
import com.cuit.entity.Voice;
import com.cuit.mapper.VoiceMapper;
import com.cuit.service.VoiceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/voices")
public class VoiceController {

    @Autowired
    private VoiceService voiceService;

    @Autowired
    private VoiceMapper voiceMapper;

    /**
     * 查询所有语音记录
     */
    @GetMapping
    public Result getVoices(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {

        PageInfo<Voice> pageInfo = voiceService.getVoices(page, size, keyword);
        PageResult result = new PageResult(pageInfo.getList(), pageInfo.getTotal());
        System.out.println(result);
        return Result.success(result);
    }


    /**
     * 更新语音记录（例如校准识别文本）
     */
    @PutMapping("/{id}")
    public Result updateVoice(
            @PathVariable("id") int id,
            @RequestBody Map<String, String> requestBody // 接收 text 字段
    ) {
        String text = requestBody.get("text");
        // 确保更新对象的 id 与 URL 中一致
        int updateCount = voiceMapper.updateText(id , text);
        if (updateCount > 0) {
            return Result.success("更新成功");
        }
        return Result.error(Constants.CODE_500, "更新失败");
    }

    /**
     * 删除语音记录
     */
    @DeleteMapping("/{id}")
    public Result deleteVoice(@PathVariable("id") int id) {
        int deleteCount = voiceMapper.deleteVoice(id);
        if (deleteCount > 0) {
            return Result.success("删除成功");
        }
        return Result.error(Constants.CODE_500, "删除失败");
    }
}
